const Order = require('../models/Orders');

// 获取订单信息
exports.getOrder = async (req, res) => {
    try {
        const order = await Order.findById(req.params.id);
        if (!order) {
            return res.status(404).json({ message: 'Order not found' });
        }
        res.json(order);
    } catch (err) {
        res.status(500).json({ message: 'Server Error', error: err });
    }
};

// 创建新订单
exports.createOrder = async (req, res) => {
    const { userId, items, totalAmount } = req.body;
    try {
        const newOrder = new Order({
            userId,
            items,
            totalAmount
        });

        await newOrder.save();
        res.status(201).json({ message: 'Order created successfully', order: newOrder });
    } catch (err) {
        res.status(500).json({ message: 'Server Error', error: err });
    }
};

// 更新订单信息
exports.updateOrder = async (req, res) => {
    const { items, totalAmount } = req.body;
    try {
        const order = await Order.findById(req.params.id);
        if (!order) {
            return res.status(404).json({ message: 'Order not found' });
        }

        order.items = items || order.items;
        order.totalAmount = totalAmount || order.totalAmount;

        await order.save();
        res.json({ message: 'Order updated successfully' });
    } catch (err) {
        res.status(500).json({ message: 'Server Error', error: err });
    }
};

// 删除订单
exports.deleteOrder = async (req, res) => {
    try {
        const order = await Order.findById(req.params.id);
        if (!order) {
            return res.status(404).json({ message: 'Order not found' });
        }

        await order.remove();
        res.json({ message: 'Order deleted successfully' });
    } catch (err) {
        res.status(500).json({ message: 'Server Error', error: err });
    }
};
